import { proxy, reqHeader, isAuthorization, limitLength, stringify, getscene, getparamstr} from '../../utils/util.js';
import LoginStore from '../login/store.js';
const app = getApp();
import async from '../../libs/async.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    galleryData:{},
    albumPhotoUrl:'',
    albumPhotoParam:{},
    self:false,
    commentCmpData:{
      id:'',
      count:0,
      iconUrl:'',
      newStyle:''
    },
    sharePop:false,
    canvasHeight: 0,
    canvasHidden: true,
    appParams: '',
  },
  likeHandler:function(e){
    if (!isAuthorization(e)) {
      return;
    }
    let me = this;
    LoginStore.validateLogin(() => {
      let userAccountInfo = LoginStore.userInfo;
      let galleryData = this.data.galleryData;
      if (userAccountInfo.userId == galleryData.uploaderId) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '无法为自己的影集点赞哟~',
          success: function (res) {

          }
        });
        return;
      }

      if (galleryData.userLikerState == undefined) {
        me.loadAlbumData(this.data.options);
        return;
      }
      let actionFlag = 1;
      if (galleryData.userLikerState) {
        actionFlag = 0;
      }
      wx.request({
        url: `${proxy}/community/doLike.do`,
        data: {
          action: actionFlag,
          likedId: galleryData.id,
          byAction: userAccountInfo.userId,
          access_token: userAccountInfo.access_token
        },
        header: reqHeader,
        success: function (res) {
          res = res.data;
          if (res.status == 200) {
            if (galleryData.userLikerState) {
              galleryData.pictureLikeedCount--;
            } else {
              galleryData.pictureLikeedCount++;
            }
            galleryData.userLikerState = !galleryData.userLikerState;
            me.setData({
              galleryData: galleryData
            });
          } else {
            console.log(res.message);
          }
        }
      });
    })
  },
  loadAlbumData: function (options){
    let galleryId = options.galleryId;
    let userInfo = LoginStore.userInfo;
    let me = this;
    wx.request({
      url: `${proxy}/community/set/${galleryId}/details?type=json`,
      data: {
        access_token: userInfo.access_token || '',
      },
      header: reqHeader,
      success: function (res) {
        if(res.statusCode != 200){
          return;
        }
        res = res.data;
        if (res.status == 200){
          let self=false;
          if (userInfo.userId && userInfo.userId == res.data.uploaderId){
            self=true;
          }
          if (!res.data.uploaderInfo.avatar.baseUrl) {
            res.data.uploaderInfo.avatar.a1 = 'https://img.500px.me/default_tx.png!a1';
          }
          me.setData({
            galleryData:res.data,
            albumPhotoUrl: `${proxy}/community/set/${galleryId}/photos`,
            albumPhotoParam:{
              startTime:'',
              page:1,
              size:20,
              type:'json'
            },
            self: self,
            commentCmpData: {
              id: res.data.id,
              count: res.data.commentCount,
              iconUrl: "https://cdn.500px.me/images/WeChat/icon_comment2.svg",
              newStyle: '__fromAlbum',
              uploaderId: res.data.uploaderId
            },
            options: options,
            appParams:JSON.stringify({
              category:"setDetail",
              id:res.data.id
            })
          })
        }else{
          console.log(res.message);
        }

      }
    });
  },
  changeStateToOpen:function(){
    let galleryData = this.data.galleryData;
    if (galleryData.privacy == 2 && galleryData.setSetCount < 2){
      wx.showModal({
        title: '提示',
        content: '至少2张才能公开哦，请到500pxAPP设置～',
        showCancel:false
      })
      return;
    }

    let me = this;
    let privacy = 2;
    if (galleryData.privacy == 2) {
      privacy = 0;
    }
    wx.request({
      url: `${proxy}/community/set/${galleryData.id}/update`,
      data: {
        jsonData: stringify({
          title: galleryData.title,
          privacy: privacy,
          description: galleryData.description,
          uploaderId: galleryData.uploaderId,
          uploaderName: galleryData.uploaderName
        }),
        access_token: LoginStore.userInfo.access_token
      },
      method: 'POST',
      header: Object.assign({
        'content-type': 'application/x-www-form-urlencoded'
      }, reqHeader),
      success: function (res) {
        if (res.statusCode != 200){
          return;
        }
        res= res.data;
        if (res.status == 200){
          galleryData.openState = res.data.openState;
          galleryData.privacy = res.data.privacy;
          me.setData({
            galleryData: galleryData
          })
        }else{
          console.log(res.message);
        }
      }
    });


  },

  sharePopShow: function () {
    if (this.data.galleryData.openState == "private"){
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '私有影集暂不支持分享~',
      });
      return;
    }
    if (this.data.galleryData.setSetCount < 2) {
      wx.showModal({
        title: '提示',
        content: '至少2张才能分享~',
        showCancel: false
      })
      return;
    }
    this.setData({
      sharePop: true
    });
  },
  closeSharePop: function (e) {
    this.setData({
      sharePop: false
    });
    if (e.detail.makePoster) {
      this.makePoster();
    }
  },
  makePoster: function () {
    wx.showLoading({
      title: '生成中...',
      mask: true
    });

    let me = this;
    let galleryData = this.data.galleryData;

    getscene(galleryData.id, (scene) => {
      let cover_obj = {
        url: galleryData.url.p3
      }

      let logo_obj = {
        url: 'https://node.500px.me/images/WeChat/logo500.png'
      }
      let avatar_obj = {
        url: galleryData.uploaderInfo.avatar.a1
      }
      let erweima_obj = {
        url: `https://node.500px.me/weChat/queryCodeImg?page=pages/album/album&scene=${scene}`
      }

      async.forEach([cover_obj, logo_obj, avatar_obj, erweima_obj], (item, callback) => {
        wx.getImageInfo({
          src: item.url,
          success: function (res) {
            item.res = res;
            callback();
          },
          fail: function (e) {
            console.log(e)
          }
        });

      }, function () {
        let canvasWidth = app.globalData.screenWidth;
        let coverBoxHeight = 203 / 375 * canvasWidth;
        let canvasHeight = coverBoxHeight + 123;

        me.setData({
          canvasHidden: false,
          canvasHeight: canvasHeight
        }, () => {
          var context = wx.createCanvasContext('myCanvas');

          context.fillStyle = "#fff";
          context.fillRect(0, 0, canvasWidth + 10, canvasHeight + 10);

          let coverImgHeight = coverBoxHeight;
          let coverImgWidth = cover_obj.res.width / cover_obj.res.height * coverImgHeight;
          let coverLeft = (coverImgWidth - canvasWidth) / 2;
          let coverTop = 0;
          if (coverImgWidth < canvasWidth) {
            coverImgWidth = canvasWidth;
            coverImgHeight = cover_obj.res.height / cover_obj.res.width * coverImgWidth;
            coverLeft = 0;
            coverTop = (coverImgHeight - coverBoxHeight) / 2;
          };
          context.save();
          context.beginPath()
          context.rect(0, 0, canvasWidth, coverBoxHeight);
          context.fill();
          context.clip()
          context.drawImage(cover_obj.res.path, -coverLeft, -coverTop, coverImgWidth + 2, coverImgHeight);
          context.restore();

          context.drawImage(logo_obj.res.path, 16, coverBoxHeight - 30, 203 / 2, 31 / 2);

          context.save();
          let r = 10;
          let d = r * 2;
          let cx = 20;
          let cy = coverBoxHeight + 65;
          context.beginPath();
          context.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
          context.setStrokeStyle('#FFFFFF');
          context.stroke();
          context.clip();
          context.drawImage(avatar_obj.res.path, cx, cy, d, d);
          context.restore();

          context.setFontSize(17);
          context.setTextAlign('left');
          context.setTextBaseline('top');
          context.setFillStyle("#525558");
          let titleText = limitLength(galleryData.title);
          context.fillText(titleText, 20, coverBoxHeight + 37);

          context.setFontSize(12);
          context.setTextAlign('left');
          context.setTextBaseline('top');
          context.setFillStyle("#B9C1C7");
          let nickNameText = limitLength(galleryData.uploaderInfo.nickName);
          context.fillText(nickNameText, 45, coverBoxHeight + 67);

          context.drawImage(erweima_obj.res.path, canvasWidth - 92, coverBoxHeight + 16, 72, 72);

          context.setFontSize(10);
          context.setTextAlign('right');
          context.setTextBaseline('top');
          context.setFillStyle("#525558");
          context.fillText('扫描或长按小程序码', canvasWidth - 11, coverBoxHeight + 93);

          context.draw(false, () => {
            setTimeout(function () {
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                fileType: 'jpg',
                success: function (res) {
                  wx.hideLoading();
                  me.setData({
                    canvasHidden: true
                  });
                  wx.previewImage({
                    current: res.tempFilePath,
                    urls: [res.tempFilePath]
                  })
                }
              })
            }, 500);
          });
        });
      })
    });

    
    

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let me = this;
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      getparamstr(scene, function (paramStr) {
        options.galleryId = paramStr;
        me.loadAlbumData(options);
      })

    } else {
      me.loadAlbumData(options);
    }  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.freshMark == undefined || !this.data.freshMark) {
      return;
    }

    let options = this.data.options;

    this.loadAlbumData(options)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      freshMark: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let params = this.data.albumPhotoParam;
    params.page++;
    this.setData({
      albumPhotoParam: params
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.galleryData.title,
      imageUrl: this.data.galleryData.url.baseUrl + '!wechat'
    }
  }
})